package com.example.smartcity_40.Fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TableLayout
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.example.smartcity_40.R
import com.example.smartcity_40.databinding.FragmentHomeragmentBinding
import com.example.smartcity_40.databinding.MHomeHotListBinding
import com.example.smartcity_40.databinding.MItemHomeNewsListBinding
import com.example.smartcity_40.databinding.MItemHomeServiceBinding
import com.example.smartcity_40.home.*
import com.example.smartcity_40.tool.*
import com.google.android.material.tabs.TabLayout

import com.example.smartcity_40.home.HomeBannerBean
import com.example.smartcity_40.tool.Tool
import com.example.smartcity_40.tool.g
import com.example.smartcity_40.tool.tool
import com.example.smartcity_40.tool.viewBinding
import com.google.gson.Gson

class Homeragment : androidx.fragment.app.Fragment() {
    private val vb by viewBinding(com.example.smartcity_40.databinding.FragmentHomeragmentBinding::inflate)
    val TAG = "Homeragment"
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        loadBanner()
        loadSeries()
        loadHot()
        loadTab()
        return vb.root
    }

    private fun loadTab() {
        tool.apply {
            send("/prod-api/press/category/list",Tool.GET,null,false,HomeTypeBean::class.java) {
                for (i in it.data) {
                    val newTab = vb.homeTab.newTab()
                    newTab.text = i.name
                    vb.homeTab.addTab(newTab)
                }
                vb.homeTab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                    override fun onTabSelected(tab: TabLayout.Tab?) {
                        try {
                            if (tab != null) {
                                loadNewsList(it.data[tab.position].id)
                            }
                        } catch (e: java.lang.Exception) {
                            Log.e(TAG, "${e.message}")
                            e.printStackTrace()
                        }
                    }

                    override fun onTabUnselected(tab: TabLayout.Tab?) {
                    }

                    override fun onTabReselected(tab: TabLayout.Tab?) {
                    }

                })
                try {
                    if (it.data.isNotEmpty()) {
                        loadNewsList(it.data[0].id)
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "loadTab: ${e.message}")
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    fun loadNewsList(tab:Int) {
        tool.apply {
            send("/prod-api/press/press/list?type=$tab",Tool.GET,null,false) {
                val data = g.fromJson(it,HomeNewsListBean::class.java).rows
                vb.homeNewsList.adapter = GenericAdapter(data.size,
                        { MItemHomeNewsListBinding.inflate(layoutInflater) }) { binding,position->
                    binding.mItemHomeNewsListTitle.text = data[position].title
                    binding.mItemHomeNewsListLikeNum.text = "点赞：${data[position].likeNum}"
                    binding.mItemHomeNewsListCommentNum.text = "阅读量：${data[position].commentNum}"
                    binding.mItemHomeNewsListContent.text = Html.fromHtml(data[position].content)
                    try {
                        Glide.with(context).load(getUrl(data[position].cover)).into(binding.mItemHomeNewsListCover)
                    } catch (e: Exception) {
                        Log.e(TAG, "loadNewsList: ${e.message}")
                    }
                    binding.root.setOnClickListener {
                        val intent = Intent(context,HomeNewsInfoActivity::class.java)
                        intent.putExtra("id",data[position].id)
                        startActivity(intent)
                    }
                }
                vb.homeNewsList.layoutManager = LinearLayoutManager(context)
            }
        }
    }

    private fun loadHot() {
        tool.apply {
            send("/prod-api/press/press/list?hot=Y",Tool.GET,null,false,HomeHotBean::class.java) {
                val data = it.rows
                vb.homeHot.adapter = GenericAdapter(it.rows.size,
                        { MHomeHotListBinding.inflate(layoutInflater) }) { binding,position->
                    binding.mItemHomeHotText.text = it.rows[position].title
                    try {
                        Glide.with(context).load(getUrl(it.rows[position].cover)).into(binding.mItemHomeHotImg)
                    } catch (e: Exception) {
                        Log.e(TAG, "loadHot: ${e.message}")
                    }
                    binding.root.setOnClickListener {
                        val intent = Intent(context,HomeNewsInfoActivity::class.java)
                        intent.putExtra("id",data[position].id)
                        startActivity(intent)
                    }
                }
                vb.homeHot.layoutManager = GridLayoutManager(context,2)
            }
        }
    }

    private fun loadSeries() {
        tool.apply {
            send("/prod-api/api/service/list",Tool.GET,null,false) {
                val data = g.fromJson(it,HomeServiceBean::class.java).rows.sortedBy { it.sort }
                vb.homeService.adapter = GenericAdapter(10,
                        { MItemHomeServiceBinding.inflate(layoutInflater) }) { binding,position->
                    if (position == 9) {
                        Glide.with(context).load(getUrl(data[position].imgUrl)).into(binding.mItemHomeServiceImgUrl)
                        binding.mItemHomeServiceName.text = "更多服务"
                        binding.root.setOnClickListener {
                            val intent = Intent("jump")
                            context.sendBroadcast(intent)
                        }
                    } else {
                        binding.mItemHomeServiceName.text = data[position].serviceName
                        Glide.with(context).load(getUrl(data[position].imgUrl)).into(binding.mItemHomeServiceImgUrl)
                        binding.root.setOnClickListener {
                            Toast.makeText(context,"未开发",Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                vb.homeService.layoutManager = GridLayoutManager(context,5)
            }
        }
    }

    private fun loadBanner() {
        tool.apply {
            send("/prod-api/api/rotation/list?pageNum=1&pageSize=8&type=2",Tool.GET,null,false) {
                val data = Gson().fromJson(it,HomeBannerBean::class.java).rows
                val list = mutableListOf<String>()
                for (i in data.indices) {
                    list.add(data[i].advImg)
                }
                Log.e(TAG, "loadBanner: $list")
                setBanner(vb.homeBanner,list)
            }
        }
    }
}